package show.me.the.money.util.context;

import java.io.Serializable;
import java.util.HashMap;

public class Context implements Serializable{
	
	private static final long serialVersionUID = 1L;
	
	public static final String APP_CONTEXT = "_applicationContext";
	public static final String WEB_SESSION = "_webSession";
	public static final String HTTP_REQUEST= "_httpRequest";
	public static final String DB_SESSION= "_dbSession";
	
	public static String topCtxName;
	private static Context topCtx;
	protected HashMap<String,Object> values = new  HashMap<String,Object>();
	protected HashMap<String,Context> ctxs = new  HashMap<String,Context>();
	
	public Context(String name,Context ctx){
		topCtxName = name;
		topCtx = ctx;
		ctxs.put(topCtxName, topCtx);
	}
	
	public Context(){
		if(topCtx != null){
			ctxs.put(topCtxName, topCtx);
		}
	}
	
	public void setCtxValues(HashMap<String,Object> values){
		this.values.putAll(values);
	}
	
	public HashMap<String,Context> getSubCtxs(){
		return this.ctxs;
	}
	
	public void setSubCtxs(HashMap<String, Context> ctxs){
		this.ctxs.putAll(ctxs);
	}
	
	public void putCtx(String name,Context ctx){
		this.ctxs.put(name,ctx);
	}
	
	public void put(String name,Object value){
		int p = name.indexOf(".");
		if(p > 0){
			String pkName = name.substring(0,p);
			name = name.substring(p + 1);
			if(ctxs.containsKey(pkName)){
				(ctxs.get(pkName)).put(name,value);
			}
		}
		else{
			this.values.put(name, value);
		}
	}
	
	public boolean has(String name){
		int p = name.indexOf(".");
		if(p > 0){
			String pkName = name.substring(0,p);
			name = name.substring(p + 1);
			if(ctxs.containsKey(pkName)){
				return (ctxs.get(pkName)).has(name);
			}
			return false;
		}
		else{
			return this.values.containsKey(name);
		}		
	}
	
	public String value(String name){
		Object v = get(name,null);
		return v != null ? String.valueOf(v) : "";
	}
	
	public String value(String name,HashMap<String,Object> arg){
		return String.valueOf(get(name,arg));
	}
	
	public Object get(String name){
		return get(name,null);
	}
	
	public Object get(String name,HashMap<String,Object> arg){
		if(name == null){
			return null;
		}
		int p = name.indexOf(".");
		if(p > 0){
			String pkName = name.substring(0,p);
			name = name.substring(p + 1);
			
			if(ctxs.containsKey(pkName)){
				return (ctxs.get(pkName)).get(name,arg);
			}
		}
		if(values.containsKey(name)){
			return values.get(name);
		}
		return null;
	}
}
